package com.chain.BrotherExchange.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.chain.BrotherExchange.R;
import com.chain.BrotherExchange.ui.core.BaseActivity;
import com.chain.BrotherExchange.ui.fragment.CoinOrderListFragment;
import com.chain.BrotherExchange.ui.fragment.LegalTenderOrderListFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 我的订单
 */
public class MyOrderActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @Bind(R.id.order_group) RadioGroup mOrderGroup;
    @Bind(R.id.arrow_back_image) View mArrowBackImage;

    private List<Fragment> mFragmentMap = new ArrayList<>();

    public static void launch(Context context) {
        context.startActivity(new Intent(context, MyOrderActivity.class));
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_my_order;
    }

    @Override
    protected void initActions() {
        mArrowBackImage.setOnClickListener(v -> onBackPressed());

        // fragment
        mFragmentMap.add(new CoinOrderListFragment());
        mFragmentMap.add(new LegalTenderOrderListFragment());

        // 切换
        mOrderGroup.setOnCheckedChangeListener(this);
        ((RadioButton) mOrderGroup.findViewById(R.id.coin_order_button)).setChecked(true);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.coin_order_button:
                switchFragment(mFragmentMap.get(0));
                break;
            case R.id.legal_tender_order_button:
                switchFragment(mFragmentMap.get(1));
                break;
        }
    }

    private void switchFragment(Fragment targetFragment) {
        if (targetFragment != null) {
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            if (!targetFragment.isAdded()) {
                fragmentTransaction.add(R.id.content_layout, targetFragment);
            }

            for (Fragment fragment : mFragmentMap) {
                if (fragment == targetFragment) {
                    fragmentTransaction.show(fragment);
                } else {
                    fragmentTransaction.hide(fragment);
                }
            }

            fragmentTransaction.commit();
        }
    }
}
